package org.csu.newpetstoreback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.newpetstoreback.common.CommonResponse;
import org.csu.newpetstoreback.entity.*;
import org.csu.newpetstoreback.persistence.*;
import org.csu.newpetstoreback.service.AccountService;
import org.csu.newpetstoreback.vo.AccountVO;
import org.csu.newpetstoreback.vo.ItemLittleVO;
import org.csu.newpetstoreback.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SignOnMapper signOnMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ItemMapper itemMapper;

    @Override
    public CommonResponse<AccountVO> getAccount(String username, String password) {
        QueryWrapper<SignOn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",DigestUtils.md5DigestAsHex(password.getBytes()));

        SignOn signOn = signOnMapper.selectOne(queryWrapper);
        if(signOn == null){
            return CommonResponse.createForNotFound(1,"用户名或密码不正确");
        }
        return getAccount(username);
    }

    @Override
    public CommonResponse<AccountVO> getAccount(String username) {
        Account account = accountMapper.selectById(username);
        SignOn signOn = signOnMapper.selectById(username);
        if(account == null){
            return CommonResponse.createForNotFound(1,"获取用户信息失败");
        }
        AccountVO accountVO = entityToAccountVO(account,signOn);
        return CommonResponse.createForSuccess(accountVO);
    }

    @Override
    public CommonResponse<Account> getAccountByName(String username) {
        Account account = accountMapper.selectById(username);
        if(account == null){
            return CommonResponse.createForNotFound(1,"用户名可用");
        }
        return CommonResponse.createForSuccess(account,"该用户已存在");
    }

    @Override
    public CommonResponse<AccountVO> getAccountByPh(String phone) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Account account = accountMapper.selectOne(queryWrapper);

        QueryWrapper<SignOn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("username",account.getUsername());
        SignOn signOn = signOnMapper.selectOne(queryWrapper1);

        AccountVO accountVO = entityToAccountVO(account,signOn);

        return CommonResponse.createForSuccess(accountVO);
    }

    @Override
    public CommonResponse<Account> isPhoneIn(String phone) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Account account = accountMapper.selectOne(queryWrapper);
        if(account == null){
            return CommonResponse.createForNotFound(1,"电话号码可用");
        }
        return CommonResponse.createForSuccess(account,"电话号码被占用");
    }


    @Override
    public CommonResponse<Account> updateAccount(AccountVO accountVO) {

        int updateAccountSuccess = -1;
//        int updateSignOnSuccess = -1;

        Account account = new Account();
//        SignOn signOn = new SignOn();

        account.setUsername(accountVO.getUsername());
        account.setEmail(accountVO.getEmail());
        account.setRealname(accountVO.getRealname());
        account.setAddress1(accountVO.getAddress1());
        account.setCity(accountVO.getCity());
        account.setCountry(accountVO.getCountry());
        account.setPhone(accountVO.getPhone());
        account.setAImage(accountVO.getAImage());

        updateAccountSuccess = accountMapper.updateById(account);

//        signOn.setUsername(accountVO.getUsername());
//        signOn.setPassword(accountVO.getPassword());
//        signOn.setPassword("");


//        updateSignOnSuccess = signOnMapper.updateById(signOn);

        if(updateAccountSuccess>0){
            return CommonResponse.createForSuccess(account);
        }
        else{
            return CommonResponse.createForUnauthorized("用户信息无更新");
        }
    }


    @Override
    public CommonResponse<AccountVO> insertAccount(String username,String password,String email) {

        int insertAccountSuccess=-1;
        int insertSignOnSuccess=-1;

        Account account = new Account();
        SignOn signOn = new SignOn();
        account.setUsername(username);
        account.setEmail(email);

        insertAccountSuccess=accountMapper.insert(account);

        signOn.setUsername(username);

//        signOn.setPassword(password);
        signOn.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        insertSignOnSuccess=signOnMapper.insert(signOn);

        if(insertAccountSuccess>0 && insertSignOnSuccess>0){
            return getAccount(username);
        }
        else{
            return CommonResponse.createForUnauthorized("注册失败");
        }

    }


    @Override
    public CommonResponse<List<OrderVO>> getOrders(String username) {
        List<OrderVO> orderVOList = new ArrayList<>();

        QueryWrapper<Order> queryWrapper0 = new QueryWrapper<>();
        queryWrapper0.eq("userid",username);
        List<Order> orderList = orderMapper.selectList(queryWrapper0);

        if(orderList.isEmpty()){
            return CommonResponse.createForNotFound("没有订单信息");
        }

        for (Order order:orderList){

            QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orderId", order.getOrderId());//column的orderId是数据库表里的小写吗？
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);

            List<ItemLittleVO> itemLittleVOList = new ArrayList<>();
            for (OrderItem orderItem:orderItemList){
                ItemLittleVO itemLittleVO = orderItemToItemLittleVO(orderItem);
                itemLittleVOList.add(itemLittleVO);
            }

            OrderVO orderVO = orderToOrderVO(order, itemLittleVOList);
            orderVOList.add(orderVO);
        }

        return CommonResponse.createForSuccess(orderVOList);
    }

    private AccountVO entityToAccountVO(Account account,SignOn signOn){
        AccountVO accountVO = new AccountVO();
        accountVO.setUsername(account.getUsername());
        accountVO.setEmail(account.getEmail());
        accountVO.setRealname(account.getRealname());
        accountVO.setAddress1(account.getAddress1());
        accountVO.setCity(account.getCity());
        accountVO.setCountry(account.getCountry());
        accountVO.setPhone(account.getPhone());
        accountVO.setAImage(account.getAImage());

//        accountVO.setPassword(signOn.getPassword());
        accountVO.setPassword((DigestUtils.md5DigestAsHex(signOn.getPassword().getBytes())));
        return accountVO;

    }

    private ItemLittleVO orderItemToItemLittleVO(OrderItem orderItem){
        ItemLittleVO itemLittleVO = new ItemLittleVO();

        Item item = itemMapper.selectById(orderItem.getItemId());

        itemLittleVO.setItemId(orderItem.getItemId());
        itemLittleVO.setQuantity(orderItem.getQuantity());
        itemLittleVO.setPrice(orderItem.getPrice());
        itemLittleVO.setIName(item.getIName());
        itemLittleVO.setIImage(item.getIImage());
        itemLittleVO.setIDescn(item.getIDescn());

        return itemLittleVO;
    }

    private OrderVO orderToOrderVO(Order order, List<ItemLittleVO> itemLittleVOList){
        OrderVO orderVO = new OrderVO();

        orderVO.setOrderId(order.getOrderId());
        orderVO.setUsername(order.getUsername());
        orderVO.setRealname(order.getRealname());
        orderVO.setOrderDate(order.getOrderDate());
        orderVO.setOrderStatus(order.getOrderStatus());
        orderVO.setShipCountry(order.getShipCountry());
        orderVO.setShipCity(order.getShipCity());
        orderVO.setAddress(order.getAddress());
        orderVO.setCourier(order.getCourier());
        orderVO.setTotalPrice(order.getTotalPrice());
        orderVO.setPayType(order.getPayType());

        orderVO.setItemList(itemLittleVOList);

        return orderVO;
    }

}
